//
//  XGL_LiveViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/13.
//

import UIKit
import FSPagerView
import MJRefresh

class XGL_LiveViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    lazy var pagerView = FSPagerView()
    lazy var pageControl = FSPageControl()
    var collectionView: UICollectionView!
    var userHeaderView: UIImageView!
    
    var pageIndex: NSInteger = 1
    let header = MJRefreshNormalHeader()
    let footer = MJRefreshBackNormalFooter()
    
    var livesData: [PublishData] = []
    var banners: [PublishData] = []{
        didSet{
            self.pageControl.numberOfPages = self.banners.count
            self.pagerView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "")
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.getPublishDataRequest()
        
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.addBlack.notificationName, object: nil)
        XGL_Notice.default.addObserver(self, selector: #selector(self.addblackNoticeAction), name: XGL_Notification.deleteBlack.notificationName, object: nil)
    }
    

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }

}

extension XGL_LiveViewController{
    @objc private func searchAction(){
        let vc = XGL_LiveSearchResultViewController()
        self.navigationController?.pushViewController(vc)
    }
    
    @objc private func refresh(){
        self.pageIndex = 1
        self.getPublishDataRequest()
    }
    @objc private func getMore(){
        self.getPublishDataRequest()
    }
    @objc private func addblackNoticeAction(notice: Notification){
        self.header.beginRefreshing()
    }
}

extension XGL_LiveViewController{
    private func reloadData(){
        self.livesData = self.livesData.filter({$0.auditUserExt?.userId.description != XGL_userDataManager.share.userId})
        self.collectionView.reloadData()
        if self.livesData.count > 5 {
            while self.banners.count < 5 {
                let data = self.randomBannerData()
                if !self.banners.contains(where: {$0.id == data.id}) {
                    self.banners.append(data)
                }
            }
        }else{
            self.banners = self.livesData
        }
    }
    private func randomBannerData()->PublishData{
        let index = Int.random(in: 0..<self.livesData.count)
        return self.livesData[index]
    }
}

extension XGL_LiveViewController{
    private func getPublishDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<PublishData>>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .GetPublishData(userId: nil, page: self.pageIndex, size: 20, data1: "1", pid: nil, data5: nil))) { result in
            switch result{
            case .success(let response):
                self.hudView.dismiss()
                if let model = response.resultData{
                    if self.header.isRefreshing{
                        self.livesData = model.data
                        self.header.endRefreshing()
                        self.footer.resetNoMoreData()
                    }else if self.footer.isRefreshing{
                        self.livesData.append(contentsOf: model.data)
                        self.footer.endRefreshing()
                    }else{
                        self.livesData = model.data
                    }
                    if model.totalPages <= model.currentPage{
                        self.footer.endRefreshingWithNoMoreData()
                    }
                    self.reloadData()
                }
                break
            default:
                self.hudView.dismiss()
                break
            }
        }
    }
}

extension XGL_LiveViewController: FSPagerViewDelegate,FSPagerViewDataSource{
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.banners.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        var cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index) as? XGL_LiveBannerItemCell
        if cell == nil {
            cell = XGL_LiveBannerItemCell()
        }
        let model = self.banners[index]
    
        cell?.itemView.itemData = model
        
        return cell!
    }
  
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
        self.pageControl.currentPage = index
        
        let model = self.banners[index]
        let vc = XGL_LiveRoomViewController()
        vc.liveId = model.id
        vc.liveData = model
        self.navigationController?.pushViewController(vc)
    }
    
    func pagerViewDidScroll(_ pagerView: FSPagerView) {
        guard self.pageControl.currentPage != pagerView.currentIndex else {
            return
        }
        self.pageControl.currentPage = pagerView.currentIndex // Or Use KVO with property "currentIndex"
    }
}

extension XGL_LiveViewController: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        self.livesData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! XGL_LiveItemCollectionViewCell
        
        cell.itemData = self.livesData[indexPath.row]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.livesData[indexPath.row]
        let vc = XGL_LiveRoomViewController()
        vc.liveId = model.id
        vc.liveData = model
        self.navigationController?.pushViewController(vc)
    }
}

extension XGL_LiveViewController: WaterfallLayoutDelegate {
    func waterfallLayout(_ waterfallLayout: WaterfallLayout, heightForItemAtIndex index: Int, itemWidth: CGFloat) -> CGFloat {
        return itemWidth
    }
    
    func colCountInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> Int { 2 }
    
    func colMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 8 }
    
    func rowMarginInWaterFlowLayout(_ WaterfallLayout: WaterfallLayout) -> CGFloat { 16 }

}


extension XGL_LiveViewController{
    private func createXglView(){
        let titleText = UILabel().then { make in
            make.textColor = .white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 34.0)
            make.text = "All Live"
        }
        self.pagerView.dataSource = self
        self.pagerView.delegate = self
        self.pagerView.automaticSlidingInterval =  3
        self.pagerView.isInfinite = true
        //self.pagerView.interitemSpacing = 50
        self.pagerView.register(XGL_LiveBannerItemCell.self, forCellWithReuseIdentifier: "cell")

        self.pageControl.numberOfPages = self.banners.count
        self.pageControl.contentHorizontalAlignment = .center
        pageControl.setFillColor(.white, for: .normal)
        pageControl.setFillColor(UIColor.hexColor("#80FFE6"), for: .selected)

        let waterfallLayout = WaterfallLayout()
        waterfallLayout.delegate = self
        collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: waterfallLayout)
        collectionView.register(XGL_LiveItemCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        
        header.setTitle("Pull down refresh", for: .idle)
        header.setTitle("Release update", for: .pulling)
        header.setTitle("Refresh...", for: .refreshing)
        header.setRefreshingTarget(self, refreshingAction: #selector(self.refresh))
        collectionView.mj_header = header
        footer.setTitle("No more data", for: .noMoreData)
        footer.setRefreshingTarget(self, refreshingAction: #selector(self.getMore))
        collectionView.mj_footer = footer
        
        self.view.addSubviews([titleText,self.pagerView,self.pageControl,self.collectionView])
        titleText.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.top.equalTo(PanNavibarH + 16.0)
        }
        self.pagerView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.left.equalTo(30.0)
            make.height.equalTo(self.pagerView.snp.width).multipliedBy(177.0/314.0)
            make.top.equalTo(titleText.snp.bottom).offset(16.0)
        }
        self.pageControl.snp.makeConstraints { (make) in
            make.width.equalTo(50)
            make.height.equalTo(10)
            make.bottom.equalTo(pagerView.snp.bottom).offset(-15)
            make.centerX.equalToSuperview()
        }

        self.collectionView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.bottom.equalToSuperview()
            make.top.equalTo(pagerView.snp.bottom).offset(20.0)
        }
    }
    
    func creatClearNavigationBar(title: String) {
        self.navigationController?.navigationBar.barStyle = .default
        setNeedsStatusBarAppearanceUpdate()
        let backColor = UIColor.clear
       
        let navView = UIView().then { make in
            make.backgroundColor = backColor
        }
        let titleView = UILabel().then { make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Semibold(fontSize: 32.0)
            make.text = title
        }
        let searchItem = UIButton().then { make in
            make.setImage(imageWithName("icon_xgl_search_white"), for: .normal)
            make.addTarget(self, action: #selector(self.searchAction), for: .touchUpInside)
        }
        self.userHeaderView = UIImageView().then({ make in
            make.layerCornerRadius = 4.0
            make.clipsToBounds = true
        })
        navView.addSubview(titleView)
        navView.addSubview(searchItem)
        navView.addSubview(userHeaderView)
        self.view.addSubview(navView)
        
        titleView.snp.makeConstraints { make in
            make.bottom.equalTo(-16.0)
            make.left.equalTo(15.0)
        }
        userHeaderView.snp.makeConstraints { make in
            make.centerY.equalTo(titleView)
            make.left.equalTo(15.0)
            make.width.height.equalTo(36.0)
        }
        searchItem.snp.makeConstraints { make in
            make.centerY.equalTo(titleView)
            make.right.equalTo(-12.0)
            make.height.equalTo(40.0)
            make.width.equalTo(40.0)
        }
        navView.snp.makeConstraints { make in
            make.centerX.top.equalToSuperview()
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(PanNavibarH)
        }
    }
}
